package com.creative.accountsdk;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.creative.accountsdk.net.XHttpHandler;
import com.creative.accountsdk.net.account.ThirdBindProtocol;
import com.creative.accountsdk.net.account.ThirdMergeProtocol;

import cz.msebera.android.httpclient.Header;
import org.json.JSONObject;
import java.util.HashMap;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * Created by yinjialiang on 15-4-2.
 */
public class ThirdBind implements Handler.Callback{
    private Activity activity;
    private View viewRoot;
    private TextView textViewWawayaya, textViewQQ, textViewWeibo, textViewWeixin;
    private AuthorizeListener authorizeListener;
    private Handler handler;
    private int platformID;
    private String thirdUID,thirdToken;
    private String thirdNickname;
    private Dialog progress;
    private static final int MSG_AUTH_CANCEL = 2;
    private static final int MSG_AUTH_ERROR= 3;
    private static final int MSG_AUTH_COMPLETE = 4;

    private final static String TAG = ThirdBind.class.getSimpleName();

    public ThirdBind(Activity activity, ViewGroup parent) {
        this.activity = activity;
        this.handler = new Handler(this);
        ShareSDK.initSDK(activity);
        viewRoot = activity.getLayoutInflater().inflate(R.layout.account_bind, parent, false);
        parent.addView(viewRoot);

        textViewWawayaya = (TextView)viewRoot.findViewById(R.id.textViewWawayaya);
        textViewQQ = (TextView)viewRoot.findViewById(R.id.textViewQQ);
        textViewWeibo = (TextView)viewRoot.findViewById(R.id.textViewWeibo);
        textViewWeixin = (TextView)viewRoot.findViewById(R.id.textViewWeixin);
        updateBind();
    }

    public void updateBind()
    {
        UserData userData = UserData.getInstance();
        textViewWawayaya.setText(userData.getLoginName(UserData.ACCOUNT_TYPE_NORMAL));
        textViewQQ.setText(userData.getLoginName(UserData.ACCOUNT_TYPE_QQ));
        textViewWeibo.setText(userData.getLoginName(UserData.ACCOUNT_TYPE_WEIBO));
        textViewWeixin.setText(userData.getLoginName(UserData.ACCOUNT_TYPE_WEIXIN));

        if(!userData.isBindWawayaya())
        {
            textViewWawayaya.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    wawayayaLogin();
                }
            });
        }
        else
        {
            textViewWawayaya.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    modifyPassword();
                }
            });
        }
        if(!userData.isBindWeixin())
        {
            textViewWeixin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    weixinLogin();
                }
            });
        }
        else
        {
            textViewWeixin.setOnClickListener(null);
        }
        if(!userData.isBindWeibo())
        {
            textViewWeibo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    weiboLogin();
                }
            });
        }
        else
        {
            textViewWeibo.setOnClickListener(null);
        }
        if(!userData.isBindQQ())
        {
            textViewQQ.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    qqLogin();
                }
            });
        }
        else
        {
            textViewQQ.setOnClickListener(null);
        }
    }

    private void modifyPassword()
    {
        Log.d(TAG, "modifyPassword");
        AccountSdk.getInstance().modifyPassword(activity, null);
    }

    private void wawayayaLogin()
    {
        AccountSdk.getInstance().bindWawayaya(activity, new OnLoginListener() {
            @Override
            public void onError(Exception e) {

            }

            @Override
            public void onComplete(JSONObject jsonObject) {
                updateBind();
            }

            @Override
            public void onCancel() {

            }
        });
    }

    private void weiboLogin()
    {
        Platform sina = ShareSDK.getPlatform(SinaWeibo.NAME);
        authorize(sina);
    }

    private void qqLogin()
    {
        Platform qq = ShareSDK.getPlatform(QQ.NAME);
        authorize(qq);
    }

    private void weixinLogin()
    {
        Platform weixin = ShareSDK.getPlatform(Wechat.NAME);
        Log.d(TAG, "authorize weixin");
        authorize(weixin);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch(msg.what) {
            case MSG_AUTH_CANCEL: {
                //取消授权
                Toast.makeText(activity, R.string.auth_cancel, Toast.LENGTH_SHORT).show();
            } break;
            case MSG_AUTH_ERROR: {
                //授权失败
                Toast.makeText(activity, R.string.auth_error, Toast.LENGTH_SHORT).show();
            } break;
            case MSG_AUTH_COMPLETE: {
                //授权成功
                Toast.makeText(activity, R.string.auth_complete, Toast.LENGTH_SHORT).show();
                Object[] objs = (Object[]) msg.obj;
                String platformName = (String) objs[0];
                Platform platform = ShareSDK.getPlatform(platformName);
                platformID = UserData.ACCOUNT_TYPE_QQ;
                if(platformName.equals(Wechat.NAME))
                {
                    platformID = UserData.ACCOUNT_TYPE_WEIXIN;
                }
                else if(platformName.equals(SinaWeibo.NAME))
                {
                    platformID = UserData.ACCOUNT_TYPE_WEIBO;
                }
                bind(platform);
            } break;
        }
        return false;
    }

    private void bind(Platform platform)
    {
        Log.d(TAG, "bind");
        thirdUID = platform.getDb().getUserId();
        thirdToken = platform.getDb().getToken();
        thirdNickname = platform.getDb().getUserName();
        String userIcon = platform.getDb().getUserIcon();
        String userGender = platform.getDb().getUserGender();
        final ThirdBindProtocol protocol = new ThirdBindProtocol(platformID, thirdUID, thirdToken, thirdNickname);
        protocol.debugUrl(DataCenter.getHttpClient());
        progress = DialogUtils.createProgress(activity);
        progress.show();
        DataCenter.getHttpClient().get(protocol.getUrl(), protocol.getParams(), new XHttpHandler(activity,progress){
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                progress.cancel();
                if(protocol.parse(response, activity))
                {
                    Log.d(TAG, "bind success");
                    if(protocol.existAccount)
                    {
                        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                        builder.setMessage(R.string.account_merge)
                                .setPositiveButton(R.string.account_button_agree, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        merge();
                                    }
                                })
                                .setNegativeButton(R.string.account_button_cancel, null);
                        builder.create().show();
                    }
                    else {
                        UserData.getInstance().init(protocol.jsonUser);
                        UserData.getInstance().write(activity);
                        updateBind();
                    }
                }
            }
        });
    }

    private void merge()
    {
        progress = DialogUtils.createProgress(activity);
        progress.show();
        final ThirdMergeProtocol protocol = new ThirdMergeProtocol(platformID, thirdUID, thirdToken, thirdNickname);
        protocol.debugUrl(DataCenter.getHttpClient());
        DataCenter.getHttpClient().get(protocol.getUrl(), protocol.getParams(), new XHttpHandler(activity, progress){
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                progress.cancel();
                if(protocol.parse(response, activity))
                {
                    Log.d(TAG, "merge success");
                    UserData.getInstance().init(protocol.jsonUser);
                    UserData.getInstance().write(activity);
                    updateBind();
                }
            }
        });
    }

    private void authorize(Platform plat)
    {
        plat.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
                Log.d(TAG, "onComplete");
                if (action == Platform.ACTION_USER_INFOR) {
                    Message msg = new Message();
                    msg.what = MSG_AUTH_COMPLETE;
                    msg.obj = new Object[]{platform.getName(), res};
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onError(Platform platform, int action, Throwable t) {
                Log.d(TAG, "onError");
                if (action == Platform.ACTION_USER_INFOR) {
                    handler.sendEmptyMessage(MSG_AUTH_ERROR);
                }
                t.printStackTrace();
            }

            @Override
            public void onCancel(Platform platform, int action) {
                Log.d(TAG, "onCancel");
                if (action == Platform.ACTION_USER_INFOR) {
                    handler.sendEmptyMessage(MSG_AUTH_CANCEL);
                }
            }
        });
        //关闭SSO授权  plat.SSOSetting(true);
        plat.SSOSetting(true);
        plat.showUser(null);
    }
}
